package com.chen.auth.listener;

import cn.hutool.core.collection.CollUtil;
import com.chen.auth.handler.AuthenticationFailureEventHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationFailureProviderNotFoundEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 认证失败事件监听器
 * @Author C_Y_J
 * @create 2022/1/13 16:36
 **/
@Component
@Slf4j
public class AuthenticationFailureEventListener implements ApplicationListener<AbstractAuthenticationFailureEvent> {

    @Resource
    AuthenticationFailureEventHandler authenticationFailureEventHandler;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @SneakyThrows
    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        // 此类型事件不传递处理 #2386
        if (event instanceof AuthenticationFailureProviderNotFoundEvent) {
            return;
        }

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        AuthenticationException authenticationException = event.getException();
        Authentication authentication = (Authentication) event.getSource();

        // 调用自定义业务实现
        authenticationFailureEventHandler.handler(request, response,authenticationException, authentication);
    }

    private boolean isUserAuthentication(Authentication authentication) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            return true;
        }
        return CollUtil.isNotEmpty(authentication.getAuthorities());
    }

}
